package controller;

import entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import serviceimpl.ProductFieldServiceImpl;
import serviceimpl.ProductServiceImpl;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLDecoder;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    ProductServiceImpl productService;

    @Autowired
    ProductFieldServiceImpl productFieldService;
    @RequestMapping(value = "/selectByTypeThree",produces = "application/json;charset=utf-8")
    public List<Product> selectByTypeThree(@RequestParam  String type) throws UnsupportedEncodingException {
            return productService.selectByTypeThree(productFieldService.selectByType(type));
    }

    @RequestMapping(value = "/selectByType",produces = "application/json;charset=utf-8")
    public List<Product> selectByType(@RequestParam  String type) throws UnsupportedEncodingException {
        return productService.selectByType(URLDecoder.decode(type,"UTF-8"));
    }

    @RequestMapping(value="/getAllType",produces = "application/json;charset=utf-8")
    public List<String> getAllType(){
        return productService.getAllType();
    }

    @RequestMapping(value="/getAllProduct",produces = "application/json;charset=utf-8")
    public List<Product> getAllProduct(){
        return  productService.getAllProduct();
    }



    @RequestMapping("/addProduct")
    public String addProduct(@RequestParam String p_type, @RequestParam String p_name, @RequestParam Integer p_num, @RequestParam  Double price, @RequestParam String intro, @RequestParam("picID") MultipartFile multipartFile, HttpServletRequest req){
        String imageNewName=System.currentTimeMillis()+multipartFile.getOriginalFilename();
        /*图片要存储的位置:是项目tatget文件下项目根目录中的文件*/
        String rootPath= req.getSession().getServletContext().getRealPath("/WEB-INF/images/");
        File file=new File(rootPath);

        try {
            InputStream is=multipartFile.getInputStream();//从文件对象获取字节输入流
            if(!multipartFile.isEmpty()){
                OutputStream os=new FileOutputStream(rootPath+imageNewName);
                int d=-1;
                while((d= is.read())!=-1){
                    os.write(d);
                }

                os.flush();
                is.close();
                os.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


}
